import os
import re

'''android device类'''
'''teky'''
class Device():

    def __init__(self, default_deviceid = None, default_index = 0):
        self.__deviceid = None
        self.__default_index = default_index
        self.__default_deviceid = default_deviceid
        self.__deviceids = []
        pass

    def set_deviceid(self,deviceid):
        '''直接指定ID'''
        self.__deviceid = deviceid

    def tryConnect(self):
        '''尝试连接手机获取deviceid 系统需要有adb.exe环境'''

        self.get_deviceid_list()
        
        if len(self.__deviceids) == 0:
            print('没有找到连接设备')
            return None
        else:
            if self.__default_deviceid is None:
                '''
                if self.__default_index < 0 or self.__default_index > len(self.__deviceids)-1:
                    print('默认连接index超出范围,默认第一个')
                    self.__default_index = 0
                if len(self.__deviceids) > 1:
                    print('找到多台连接设备，选择第' + str(self.__default_index+1) + '台')
                self.__deviceid = self.__deviceids[self.__default_index]
                '''
                if self.__default_index < 0 or self.__default_index > len(self.__deviceids)-1:
                    print('默认连接index超出范围,没有找到指定设备')
                    return None
                else:
                    self.__deviceid = self.__deviceids[self.__default_index]
                    
            elif self.__default_deviceid in self.__deviceids:
                self.__deviceid = self.__default_deviceid
                print('找到指定连接设备')
            else:
                print('没有找到指定连接设备')
                return None

            print('连接设备编号:'+ self.__deviceid)
            return self.__deviceid
    
    def get_deviceid_list(self):
        '''返回一个当前deviceid list'''

        rt = os.popen('adb version').read()

        if rt == '':
            print('缺少adb环境')
        else:
            print(rt)

        rt = os.popen('adb devices').readlines()
        if len(rt) > 2:
            #if not rt.findall('error') >= 0 or not rt.findall('offline') >= 0
            #and rt.findall('unauthorized')
            for devicestr in rt:
                if devicestr.find('\tdevice') >= 0:
                    deviceid = devicestr.split('\t')[0]
                    self.__deviceids.append(deviceid)
        
        return self.__deviceids

